<?php


// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

class sagepay extends JObject {         
	var $ipn_data = array();         
	var $config;  
   	function __construct($config) { 
   		if (!isset($config->pay_to_email))   	  
   		{
			$config->merchant_id = '';
   			$config->pay_to_email = '';
   			$config->merchant_url = '';
   			$config->currency = '';
   			$config->status_url = '';
   			$config->return_url = '';
   			$config->cancel_url = '';
   			$config->secret_word = '';
   		}
      $this->config = $config;
//      $this->config->pay_to_email = $this->config->email;
      $this->config->server = $this->config->merchant_url;
   	}
      	
	function config_form(){
		global $mainframe, $option;
		/* Fill in the config tag below. Note that need not write the form */
		?>			    
	<tr>
      <td class="key"><?php echo JText::_('SagePay account email');?></td>
      <td>
      <input type="text" name="moneybooker[pay_to_email]" size="29" value="<?php echo $this->config->pay_to_email; ?>"></td>
    </tr>
    <tr>
      <td class="key"><?php echo JText::_('SagePay merchant ID');?></td>
      <td>
      <input type="text" name="moneybooker[merchant_id]" size="29" value="<?php echo $this->config->merchant_id; ?>"></td>
    </tr>
    <tr>
      <td class="key"><?php echo JText::_('SagePay Merchant URL');?></td>
      <td>
      	  <input size="90" type="text" value="<?php echo $this->config->merchant_url; ?>" name="moneybooker[merchant_url]" />
      </td>
    </tr>
    <tr>
      <td class="key"><?php echo JText::_('SagePay Currency');?></td>
      <td>
	      <input type="text" name="moneybooker[currency]" size="29" value="<?php echo $this->config->currency; ?>"><br>
      </td>
    </tr>
    
    <tr>
      <td class="key"><?php echo JText::_('VPSProtocol');?></td>
      <td>
	      <input type="text" name="sagepay[VPSProtocol]" size="29" value="<?php if ( isset($this->config->VPSProtocol) ) echo $this->config->VPSProtocol;  else  echo "2.23"; ?>"><br>
      </td>
    </tr>
    <tr>
      <td class="key"><?php echo JText::_('TXType');?></td>
      <td>
	      <input type="text" name="sagepay[TXType]" size="29" value="<?php if ( isset($this->config->VPSProtocol) ) echo $this->config->TXType;  else  echo "PAYMENT"; ?>"><br>
      </td>
    </tr>
    <tr>
      <td class="key"><?php echo JText::_('Vendor ID');?></td>
      <td>
	      <input type="text" name="sagepay[Vendor]" size="29" value="<?php if ( isset($this->config->Vendor) ) echo $this->config->Vendor; ?>"><br>
      </td>
    </tr>
    
	<tr>
      <td class="key"><?php echo JText::_('Moneybookers Status URL');?></td>
      <td>
	      <input type="text" name="moneybooker[status_url]" size="90" value="<?php echo $this->config->status_url; ?>"><br>
	      <small><?php echo JText::_('Eg'); ?>: <b><?php echo JRoute::_(JURI::root()."index.php?option=$option&view=japayment&task=payment_notify&payment_method=".$this->config->name); ?></b> <br/>
		  	 	<?php echo JText::_(" Note: This URL should also be entered as the 'Status URL' on the 'Website Payment Preferences in your PayPal account")?></small>
      </td>
    </tr>

	<tr>
      <td class="key"><?php echo JText::_('Moneybookers Return URL.');?></td>
      <td>
	      <input type="text" name="moneybooker[return_url]" size="90" value="<?php echo $this->config->return_url; ?>">
	      <small><?php echo JText::_('Eg'); ?>: <b><?php echo JRoute::_(JURI::root()."index.php?option=$option&view=japayment&task=payment_notify&payment_method=".$this->config->name) ?></b> <br/>
		  	 	<?php echo JText::_(" Note: This URL should also be entered as the 'Return URL' on the 'Website Payment Preferences in your PayPal account")?></small>
      </td>
    </tr>
	<tr>
      <td class="key"><?php echo JText::_('SagePay Cancel URL');?></td>
      <td>
	      <input type="text" name="moneybooker[cancel_url]" size="90" value="<?php echo $this->config->cancel_url; ?>">
	      <br/>
		  <small><?php echo JText::_('Eg'); ?>: <b><?php echo JRoute::_(JURI::root()."index.php?option=$option&view=japayment&layout=payment_cancel&payment_method=".$this->config->name)?></b></small>
      </td>
    </tr>
	<tr>
      <td class="key"><?php echo JText::_('Moneybookers secret word');?></td>
      <td>
	      <input type="text" name="moneybooker[secret_word]" size="90" value="<?php echo $this->config->secret_word; ?>">
      </td>
    </tr>
    
	<input name="name" value="moneybooker" type="hidden">	  		
		<?php
	}
	
	function more_info(){
		
	}		
   
	/**
	* Process notification post from paypal
	*
	*/
	function check_payment(){
		
		//Get 2Checkout config
		$db	= JFactory::getDBO();
		$query = "SELECT * FROM #__ja_paymentconfig WHERE name='moneybooker'";
		$db->setQuery($query);
		$payment = $db->loadObject();
		$payment->datas = new JParameter($payment->datas);
		
		global $jbconfig, $mainframe;
		$postipn = $this->toParamsString($_POST);
//		if (JRequest::getVar('merchant_id')!='') { 

			$merchant_id = JRequest::getVar('merchant_id');
			$transaction_id = JRequest::getVar('transaction_id');
			$secret = strtoupper(md5($payment->datas->get('secret_word')));
			$mb_amount = JRequest::getVar('mb_amount');
			$mb_currency = JRequest::getVar('currency');
			$status = JRequest::getVar('status');
			$md5sig = JRequest::getVar('md5sig');
			$product_type = substr($transaction_id, 0, 1);// 'P' or 'S'
			$txn_id = JRequest::getVar('mb_transaction_id');
			$invoice_id = substr($transaction_id, 1);			
			$working_sig = strtoupper (md5($merchant_id.$transaction_id.$secret.$mb_amount.$mb_currency.$status));

			if (strcmp($working_sig, $md5sig )==0) {
				$sql="SELECT count(*) FROM #__ja_transactions WHERE txn_id='$txn_id'";
				$db->setQuery($sql);
				$total = $db->loadResult();
				if($total){
					return false;
				}
				else{
					$db->setQuery("SELECT * FROM #__ja_transactions WHERE id = ".$invoice_id.";");
					$ret = $db->loadObject();
					$ret->txn_id = $txn_id;
					switch ($status) {
						case "-2":
							break;
						case "2":
							$ret->completed = 1;
							$ret->datas = $this->ipn_data;
							return $ret;
							break;
						case "1": // scheduled (wait for 2 or -2)
							$ret->completed = 0;
							$ret->datas = $this->ipn_data;
							return $ret;
							break;
						case "0": // pending	
						case "-1": // cancelled
							$ret->datas = $this->ipn_data;
							$ret->completed = 0;
							return $ret;
							break;
					}
					return false;
					
				}

			} else {
					return false;
			}

//		}
//		else 
//		 return false;		

	}
	
	function toParamsString($vars){
		$postipn = "";
		foreach ($vars as $ipnkey => $ipnval)
		{
			$this->ipn_data["$ipnkey"] = $ipnval;
			$postipn.='&'.@$ipnkey.'='.urlencode(@$ipnval); 
		} // Notify string
		return $postipn;
	}
	

	
	function payment_return() {
		$db	= JFactory::getDBO();
		$query = "SELECT * FROM #__ja_paymentconfig WHERE name='moneybooker'";
		$db->setQuery($query);
		$payment = $db->loadObject();
		$payment->datas = new JParameter($payment->datas);
		
		global $jbconfig, $mainframe;
		$postipn = $this->toParamsString($_POST);
		
		if (JRequest::getVar('transaction_id')!='')
		{
			$transaction_id = JRequest::getVar('transaction_id');
			$msid = JRequest::getVar('msid');
			$working_msid = strtoupper(md5($payment->datas->get('merchant_id').$transaction_id.strtoupper(md5($payment->datas->get('secret_word')))));
			if (strcmp($msid,$working_msid)==0)
			{
				$query = "SELECT * FROM #__ja_transactions WHERE id=".substr($transaction_id,1);
				$db->setQuery($query);
				$ret = $db->loadObject();
				if (!$ret->txn_id)
				{
					$ret->txn_id = $msid;
					$ret->completed = 1;
//					$db->setQuery("UPDATE #__ja_transactions SET completed=1,txn_id='$msid' WHERE id=".substr($transaction_id,1));
//					$db->query();
					return $ret;
				}
				?>
		<div id="Mod18" class="jamod module">
		<div>
		<div>
			<div>
			
				<div class="jamod-content" style="overflow: hidden;">
					<?php echo JText::_("Your moneybooker payment has been completed successfully.")?><br/>
					<?php echo JText::_("You will receive an email with information about the status of your transaction within minutes.")?><br/>
					<?php echo JText::_("If you do not receive the email within 20 minutes, please <b>contact us</b>.")?><br/>
				</div>
			</div>
		</div>
		</div>
		</div>
		
		<?php	
				$ret = new stdClass();
				return $ret;
			}
		}
		else 
		{
			return false;
		}
			
	}
	
	function payment_cancel() {
		JError::raiseNotice(1,JText::_("You hvae cancelled the moneybooker payment or the payment was not completed."));
		JError::raiseNotice(1,JText::_("Please feel free to contact us if your experience was not as it should be."));
	}
	
	function assign_params($vars,$values,$payment)
	{
		
		$vars['pay_to_email'] = $payment->config->pay_to_email;
		$vars['transaction_id'] = $values['item_number'];
		$vars['amount'] = $values['amount'];
		$vars['status_url'] = $payment->config->status_url;
		$vars['return_url'] = $payment->config->return_url;
		$vars['cancel_url'] = $payment->config->cancel_url;
		$vars['currency'] = $payment->config->currency;
		return $vars;
	}
}
?>